package com.xyh.web.context;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * 准备一个监听器，保存了父容器
 * 监听器是Tomcat自己加载完当前web应用后会调用contextInitialized【这里会初始化容器】
 */
public class ContextLoaderListener implements ServletContextListener {
	private ApplicationContext context;
	public ContextLoaderListener(ApplicationContext context) {
		this.context = context;
	}

	@Override
	public void contextInitialized(ServletContextEvent event) { //根容器初始化
		System.out.println("ContextLoaderListener.contextInitialized");
		initWebApplicationContext(event.getServletContext()); //初始化webioc容器
	}

	private void initWebApplicationContext(ServletContext servletContext) {
		if (servletContext.getAttribute(ApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
//			throw new IllegalStateException("已经存在根容器");
			return;
		}
		if (this.context == null) {
			this.context = new ApplicationContext();
		}

		ApplicationContext wac = this.context;
		configureAndRefreshWebApplicationContext(wac, servletContext);
		servletContext.setAttribute(ApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
	}

	private void configureAndRefreshWebApplicationContext(ApplicationContext wac, ServletContext servletContext) {
		wac.setServletContext(servletContext);
		wac.refresh();
	}

}
